package com.lagou.edu.controller;

import com.lagou.edu.pojo.User;
import com.lagou.edu.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;


@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CodeService codeService;

    @RequestMapping("/create/{username}")
    public String  createCode(@PathVariable String username){
        int code = (int)((Math.random()*9+1)*100000);
        User user = new User();
        user.setCode(Integer.toString(code));
        user.setEmail(username);
        user.setCreatetime(new Date());
        long l = System.currentTimeMillis() + 10 * 60 * 1000;
        user.setExpiretime(new Date(l));
        codeService.saveCodeIntoDatabaseByEmail(user);
        //TODO 调用邮箱服务发送验证码
        String url = "http://lagou-service-email/email/" + username + "/" + code;
        String  responseCode = restTemplate.getForObject(url, String.class);
        return responseCode;
    }

    @RequestMapping("/validate/{email}/{code}")
    public String validateCode(@PathVariable(value = "email") String email,@PathVariable(value = "code") String code){
        Date expireTime = codeService.getExpireTimeByEmailAndCode(email,code);
        if (expireTime==null||expireTime.toString().isEmpty()) {
            // 错误
            return "1";
        }
        if (expireTime.getTime() >= new Date().getTime()) {
            // 正确
            return "0";
        }else{
            // 超时
            return "2";
        }
    }

}
